from django.shortcuts import render
from rest_framework.decorators import api_view, permission_classes, authentication_classes
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from rest_framework.response import Response
from rest_framework_simplejwt.authentication import JWTAuthentication
from .models import SystemSetting
from django.contrib.auth import get_user_model
from movie.models import Movie
from django.db.models import Count
from django.utils import timezone
import psutil
import os

# 默认系统设置
DEFAULT_SETTINGS = [
    # 数据清洗设置
    {
        'key': 'clean_threshold',
        'value': 30,
        'description': '数据清洗阈值（天）'
    },
    # 数据分析设置
    {
        'key': 'analysis_range',
        'value': 30,
        'description': '分析时间范围（天）'
    },
    # 数据管理设置
    {
        'key': 'data_retention',
        'value': 90,
        'description': '数据保留天数'
    },
    # 用户管理设置
    {
        'key': 'session_timeout',
        'value': 24,
        'description': '会话超时时间（小时）'
    }
]

def init_default_settings():
    """初始化默认系统设置"""
    for setting in DEFAULT_SETTINGS:
        SystemSetting.objects.get_or_create(
            key=setting['key'],
            defaults={
                'value': setting['value'],
                'description': setting['description']
            }
        )

@api_view(['GET'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
def get_settings(request):
    """获取系统状态信息"""
    try:
        User = get_user_model()
        
        # 系统基础信息
        system_info = {
            'cpu_usage': psutil.cpu_percent(interval=None),  # 不等待，立即返回
            'memory_usage': psutil.virtual_memory().percent,
            'disk_usage': psutil.disk_usage('/').percent,
        }
        
        # 数据统计
        data_stats = {
            'total_movies': Movie.objects.count(),
            'total_users': User.objects.count(),
            'active_users': User.objects.filter(is_active=True).count(),
            'admin_users': User.objects.filter(is_admin=True).count(),
        }
        
        # 数据分析
        now = timezone.now()
        last_week = now - timezone.timedelta(days=7)
        data_analysis = {
            'new_movies_week': Movie.objects.filter(created_at__gte=last_week).count(),
            'updated_movies_week': Movie.objects.filter(updated_at__gte=last_week).count(),
        }
        
        # 系统运行状态
        system_status = {
            'python_version': os.sys.version.split()[0],
            'database_type': 'MySQL',
            'server_timezone': timezone.get_current_timezone_name(),
        }

        data = {
            'system_info': system_info,
            'data_stats': data_stats,
            'data_analysis': data_analysis,
            'system_status': system_status,
        }
        
        return Response({
            'status': 'success',
            'data': data
        })
    except Exception as e:
        return Response({
            'status': 'error',
            'message': str(e)
        }, status=500)

@api_view(['POST'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAdminUser])
def update_settings(request):
    """更新系统设置"""
    try:
        settings_data = request.data
        for item in settings_data:
            setting, created = SystemSetting.objects.update_or_create(
                key=item['key'],
                defaults={
                    'value': item['value'],
                    'description': item.get('description')
                }
            )
        return Response({
            'status': 'success',
            'message': '设置更新成功'
        })
    except Exception as e:
        return Response({
            'status': 'error',
            'message': str(e)
        }, status=500)
